﻿namespace IBTrader.Modules.HistoricalData
{
    using AxTWSLib;
    using System;
    using System.Linq;

    class Error
    {
        private readonly HistoricalData main;
        internal event EventHandler PacingViolation;
        internal bool Failed;
        internal bool Paused;
        public Error(HistoricalData main)
        {
            this.main = main;
        }
        internal void Handle(_DTwsEvents_errMsgEvent e)
        {
            if (e.errorCode == 162) // Historical market data Service error message.
            {
                if (e.errorMsg.Contains("Historical data request pacing violation"))
                {
                    if (PacingViolation != null) PacingViolation(this, EventArgs.Empty);
                }
                else 
                {
                    Failed = true;
                    main.Next();
                }
            }
            else if (e.errorCode == 1100) // Connectivity between IB and TWS has been lost.
            {
                Paused = true;
            }
            else if (e.errorCode == 1102) // Connectivity between IB and TWS has been restored- data maintained.
            {
                if (Paused)
                {
                    Paused = false;
                    main.Data.Request();
                }
            }
            else if (new[] { 200, 321, 322 }.Contains(e.errorCode)) // no security definition, no duration, duplicate
            {
                Failed = true;
                main.Next();
            }
        }
    }
}
